package com.shop.cloud.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;

public class UploadApkFileUtil {
     //服务器上的生产保存路径
    public static String SAVE_FILE_URL = "/opt/static/apps/android/";

    //服务器上的测试保存路径
   // public static String SAVE_FILE_URL = "/opt/static/apps/android-test/";
    //本地
   //public static String SAVE_FILE_URL = "D:/123/";

    public static String FILEDIR = null;
    /**
     * 上传单个文件，并返回其在服务器中的存储路径
     *
     * @param aFile
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static   String uploadFile(MultipartFile aFile) throws IOException {
        String filePath = initFilePath(aFile.getOriginalFilename());
        try {
            write(aFile.getInputStream(), new FileOutputStream(filePath));
        } catch (FileNotFoundException e) {
            System.out.println("上传的文件: " + aFile.getName() + " 不存在！！");
            e.printStackTrace();
        }
        return filePath;
    }

    /***
     *
     * @param inputStream 文件流
     * @return
     * @throws Exception
     */
    public static String uploadApk(InputStream inputStream,String fileName) throws Exception {
        long  startTime=System.currentTimeMillis();
        String localPath = SAVE_FILE_URL;
        String pareName = "/"+ fileName;
        FileOutputStream fos = null;
        byte[] buffer = new byte[4096];
        int temp = 0;
        try {
            File file = new File(localPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File fileIs = new File(SAVE_FILE_URL);
            File fileIsNot = new File(SAVE_FILE_URL+pareName);
            if(fileIsNot.exists()){
            	InputStream is = new FileInputStream(SAVE_FILE_URL+pareName);
            	FileOutputStream fosCopy = new FileOutputStream(fileIs + new String(("/copy_"+fileName).getBytes(),"UTF-8"));
            	 while (true) {
                     temp = is.read(buffer, 0, buffer.length);
                     if (temp == -1) {
                         break;
                     }
                     fosCopy.write(buffer, 0, temp);
                 }
                 try {
                     if(null != fosCopy){
                         fosCopy.close();
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                     throw new Exception("生成本地文件关闭文件流异常！");
                 }
            }
            fos = new FileOutputStream(file + new String(pareName.getBytes(),"UTF-8"));
            //fos = new FileOutputStream(file + papersName);
            while (true) {
                temp = inputStream.read(buffer, 0, buffer.length);
                if (temp == -1) {
                    break;
                }
                fos.write(buffer, 0, temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("生成本地文件异常");
        } finally {
            try {
                if(null!=fos){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("生成本地文件关闭文件流异常！");
            }
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("上传文件的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return fileName;
    }
    /**
     * 写入数据
     *
     * @param in
     * @param out
     * @throws IOException
     */
    private static void write(InputStream in, OutputStream out) throws IOException {
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException ex) {
            }
        }
    }


    /**
     * 返回文件存储路径，为防止重名文件被覆盖，在文件名称中增加了随机数
     * @param name
     * @return
     */
    private static String initFilePath(String name) {
        String dir = getFileDir(name) + "";
        File file = new File(FILEDIR + dir);
        if (!file.exists()) {
            file.mkdir();
        }
        Long num = new Date().getTime();
        Double d = Math.random() * num;
        return (file.getPath()+name);
    }

    /**
     *
     * @param name
     * @return
     */
    private static int getFileDir(String name) {
        return name.hashCode() & 0xf;
    }

}
